package com.manor.im.dialog

import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.FullScreenPopupView
import com.manor.common.dialog.XToast
import com.manor.common.http.HttpSignCallback
import com.manor.common.ktx.toBean
import com.manor.common.utils.L
import com.manor.im.R
import com.manor.im.bean.GroupSearchBean
import com.manor.im.bean.GroupSearchChild
import com.manor.im.http.ImHttpUtil
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import kotlinx.android.synthetic.main.dialog_group_search.view.*

/**
 * 搜索群聊
 * @date  2020/7/24  17:52
 * @version 1.0
 */
class GroupSearchDialog(context: Context) : FullScreenPopupView(context) {

    private var pageNum = 1
    private var mAdapter: MAdapter? = null


    companion object{
        fun load(context: Context){
            XPopup.Builder(context)
                    .asCustom(GroupSearchDialog(context))
                    .show()
        }
    }

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_group_search
    }

    override fun onCreate() {
        super.onCreate()
        mAdapter = MAdapter(R.layout.item_group_recommend, mutableListOf())
        mRecycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        mRecycler.adapter = mAdapter
        mAdapter?.setOnItemChildClickListener(itemChildClickListener)
        etSearch.addTextChangedListener(editListener)
        tvDismiss.setOnClickListener { dismiss() }

    }

    private fun doSearch(key: String) {
        ImHttpUtil.getGroupSearch(key, pageNum.toString(), object : HttpSignCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                if (code == 0 && info != null && info.isNotEmpty()) {
                    val mBean = info.toBean<GroupSearchBean>()
                    mAdapter?.setNewInstance(mBean.list)
                    mAdapter?.notifyDataSetChanged()

                }
            }

        })
    }

    private fun addGroup(id: String) {
        val content: String = ""
        if (TextUtils.isEmpty(id)) {
            return
        }
        V2TIMManager.getInstance().joinGroup(id, content, object : V2TIMCallback {
            override fun onError(code: Int, desc: String) {
                L.e("Error code = $code, desc = $desc")
                //ToastUtil.toastShortMessage("Error code = $code, desc = $desc")
            }

            override fun onSuccess() {
                context?.let {
                    XToast.load(it, "\uD83D\uDE03申请成功，已通知管理员尽快处理")
                }
            }
        })
    }

    private val editListener = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            s?.run {
                doSearch(this.toString())
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    }

    private val itemChildClickListener = OnItemChildClickListener { adapter, view, pos ->
        if (view.id == R.id.tvAdd) {
            val item = adapter.data[pos] as GroupSearchChild?
            item?.run {
                addGroup(this.groupId)
            }
        }
    }


    private class MAdapter(layoutResId: Int, data: MutableList<GroupSearchChild>?)
        : BaseQuickAdapter<GroupSearchChild, BaseViewHolder>(layoutResId, data) {

        init {
            addChildClickViewIds(R.id.tvAdd)
        }

        override fun convert(holder: BaseViewHolder, item: GroupSearchChild) {
            item?.run {

                Glide.with(holder.getView<ImageView>(R.id.ivImage))
                        .load(this.faceUrl)
                        .circleCrop()
                        .into(holder.getView(R.id.ivImage))

                holder.setText(R.id.tvContent, "群介绍：$introduction")
                        .setText(R.id.tvTitle, name)
                        .setVisible(R.id.tvAdd ,isInto != "1")


            }
        }

    }

}